//
//  ChatViewController.m
//  NuwaRobot
//
//  Created by Kendama on 2017/12/7.
//  Copyright © 2017年 Kendama. All rights reserved.
//

#import "ContactsViewController.h"
#import "ContactsTableViewCell.h"
#import "ContactsSectionHeaderView.h"
#import "EaseMessageViewController.h"
#import "ChatViewController.h"
#import "GetHuanXinFriendListApi.h"
#import "FriendModel.h"
#import "BindDeviceView.h"
#import "ScanDeviceViewController.h"
#import "GetUserDeviceApi.h"
#import "NewMessageModel.h"

@interface ContactsViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) NSMutableArray *dataSource;
@property(nonatomic,copy) NSString *domain;
@property(nonatomic,strong) BindDeviceView *bindDeviceView;

@end

@implementation ContactsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNewMessage:) name:HuanXinNewMessage object:nil];
    
    
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self updateDataSource];

    [self getUserDevice];
    [self updateDatabase];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark --- 点击事件
- (void)didClickScanDeviceButton
{
    ScanDeviceViewController *vc = [ScanDeviceViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 数据刷新
- (void)getUserDevice
{
    if ([EXRACT_OBJECT(DEVICEID) isEqualToString:@"0"] || !EXRACT_OBJECT(DEVICEID)) // 没有设备
    {
        GetUserDeviceApi *api = [[GetUserDeviceApi alloc] init];
        [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
            NSDictionary *dict = request.responseJSONObject[@"data"];
            NSString *deviceID = dict[@"device_id"];
            if ([deviceID intValue] == 0) // 没有绑定设备
            {
                self.bindDeviceView.hidden = NO;
            }
            else
            {
                self.bindDeviceView.hidden = YES;
            }
            SAVE_OBJECT(deviceID, DEVICEID);
            SAVE_OBJECT(dict[@"sn"], DEVICEMAC);
        } failure:nil];
    }
    else
    {
        self.bindDeviceView.hidden = YES;
    }
    
}

- (void)receiveNewMessage:(NSNotification *)notification
{
    NSDictionary *dict = notification.userInfo;
    for (FriendModel *model in self.dataSource.lastObject)
    {
        if ([dict[@"uid"] isEqualToString:model.uid])
        {
            model.count = @"1";
            [model updateObject];
        }
    }
    
    [self updateDatabase];
}

- (void)updateDatabase
{
    NSArray *userList = [FriendModel selectFromClassAllObject];
    NSArray *array = [NewMessageModel selectFromClassAllObject];
    for (NewMessageModel *message in array)
    {
        for (FriendModel *friend in userList)
        {
            if ([message.uid isEqualToString:friend.uid])
            {
                friend.count = @"1";
                [friend updateObject];
            }
        }
    }
    NSArray *data = [FriendModel selectFromClassAllObject];
    if (data.count > 0)
    {
        [self.dataSource setObject:data atIndexedSubscript:1];
    }
    [self.tableView reloadData];
}

//- (void)updateDatabase
//{
//    NSArray *userList = [FriendModel selectFromClassAllObject];
//    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
//    for (EMConversation *conversation in conversations)
//    {
//        for (FriendModel *friend in userList)
//        {
//            if ([conversation.conversationId isEqualToString:friend.uid])
//            {
//                friend.count = @"1";
//                [friend updateObject];
//            }
//        }
//    }
//    NSArray *data = [FriendModel selectFromClassAllObject];
//    if (data.count > 0)
//    {
//        [self.dataSource setObject:data atIndexedSubscript:1];
//    }
//    [self.tableView reloadData];
//
//}

- (void)updateDataSource
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        EMError *error = nil;
//        NSArray *rooms = [[EMClient sharedClient].groupManager getJoinedGroups];
//        if (rooms)
//        {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self.dataSource setObject:rooms atIndexedSubscript:0];
//                [self.tableView reloadData];
//            });
//        }
        [[EMClient sharedClient].groupManager getJoinedGroupsFromServerWithPage:0 pageSize:-1 completion:^(NSArray *aList, EMError *aError) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (aList != nil)
                {
                    [self.dataSource setObject:aList atIndexedSubscript:0];
                    [self.tableView reloadData];
                }
            });
        }];
        

        
        GetHuanXinFriendListApi *api = [[GetHuanXinFriendListApi alloc] init];
        [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {
            NSDictionary *dict = request.responseJSONObject;
            self.domain = dict[@"domain"];
            [FriendModel deleteFromClassAllObject];
            for (NSDictionary *dic in dict[@"data"])
            {
                FriendModel *model = [[FriendModel alloc] init];
                model.uid = dic[@"uid"];
                model.nickname = dic[@"nickname"];
                model.image = [NSString stringWithFormat:@"%@%@",dict[@"domain"],dic[@"image"]];
                model.sex = dic[@"sex"];
                [model insertObject];
            }
//            NSArray *userList = [NSArray yy_modelArrayWithClass:[FriendModel class] json:dict[@"data"]];
//            NSArray *userList = [FriendModel selectFromClassAllObject];
//            if (userList.count > 0)
//            {
//                [self.dataSource setObject:userList atIndexedSubscript:1];
//                [self.tableView reloadData];
//            }
            [self updateDatabase];
            
//            FriendModel *myModel = [[FriendModel alloc] init];
//            myModel.uid = EXRACT_OBJECT(UID);
//            myModel.nickname = EXRACT_OBJECT(NICKNAME);
//            myModel.image = EXRACT_OBJECT(IMAGE);
//            [myModel insertObject];

        } failure:nil];
        
        
//        NSArray *userlist = [[EMClient sharedClient].contactManager getContactsFromServerWithError:&error];
//        if (!error) {
//            NSLog(@"获取成功 -- %@",userlist);
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self.dataSource setObject:userlist atIndexedSubscript:1];
//                [self.tableView reloadData];
//            });
//        }
    });

}

#pragma mark --- tabelview代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = self.dataSource[section];
    return array.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return px1920Height(200);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return px1920Height(80);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return px1920Height(100);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    ContactsSectionHeaderView *headView = [[ContactsSectionHeaderView alloc] init];
    if (section == 0)
    {
        headView.iconImageView.image = imageWithName(@"icon_my");
        headView.nameLabel.text = @"群组";
    }
    else
    {
        headView.iconImageView.image = imageWithName(@"icon_member");
        headView.nameLabel.text = @"成员";
    }
    return headView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ContactsTableViewCell *cell = [ContactsTableViewCell cellWithTableView:tableView forIndexPath:indexPath];
    if (indexPath.section == 0)
    {
        EMGroup *group = self.dataSource[0][indexPath.row];
        cell.nameLabel.text = group.subject;
        cell.iconImageView.image = imageWithName(@"qun");
        NSArray *array = [NewMessageModel selectFromClassPredicateWithFormat:[NSString stringWithFormat:@"where uid = '%@'",group.groupId]];
        if (array.count > 0)
        {
            cell.countLabel.hidden = NO;
        }
        else
        {
            cell.countLabel.hidden = YES;
        }
    }
    else
    {
        FriendModel *model = self.dataSource[1][indexPath.row];
        [cell setFriendWithModel:model];
//        NSString *url = [NSString stringWithFormat:@"%@%@",self.domain,model.image];
        [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:model.image] placeholderImage:imageWithName(@"robot_head")];
        if ([model.nickname isEqualToString:@""])
        {
            cell.nameLabel.text = @"我的机器人";
            cell.iconImageView.image = imageWithName(@"robot_head");
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.section == 0)
    {
        EMGroup *group = self.dataSource[0][indexPath.row];
        ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:group.groupId conversationType:EMConversationTypeGroupChat];
        chatController.hidesBottomBarWhenPushed = YES;
        chatController.navTitle = group.subject;
        
        [NewMessageModel deleteFromClassPredicateWithFormat:[NSString stringWithFormat:@"where uid = '%@'",group.groupId]];

        [self.navigationController pushViewController:chatController animated:YES];
    }
    else if(indexPath.section == 1)
    {
        FriendModel *model = self.dataSource[1][indexPath.row];
        NSString *chat = model.uid;
        // 未读消息置零
        model.count = @"0";
        [model updateObject];
        [NewMessageModel deleteFromClassPredicateWithFormat:[NSString stringWithFormat:@"where uid = '%@'",model.uid]];
        
        ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:chat conversationType:EMConversationTypeChat];
        chatController.avatar = [NSString stringWithFormat:@"%@%@",self.domain,model.image];

//        EaseMessageViewController *chatController = [[EaseMessageViewController alloc] initWithConversationChatter:@"23" conversationType:EMConversationTypeChat];
        chatController.hidesBottomBarWhenPushed = YES;
        chatController.navTitle = model.nickname;
        if ([model.nickname isEqualToString:@""])
        {
            chatController.navTitle = @"我的机器人";
        }
        [self.navigationController pushViewController:chatController animated:YES];
    }

}


#pragma mark --- 懒加载
- (UITableView *)tableView
{
    if(!_tableView)
    {
        UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        [superView addSubview:_tableView];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
    }
    return _tableView;
}

- (NSMutableArray *)dataSource
{
    if(!_dataSource)
    {
        _dataSource = [[NSMutableArray alloc]initWithArray:@[@[],@[]]];
    }
    return _dataSource;
}

- (BindDeviceView *)bindDeviceView
{
    if(!_bindDeviceView)
    {
        UIView *superView = self.view;
        _bindDeviceView = [[BindDeviceView alloc]init];
        [superView addSubview:_bindDeviceView];
        [_bindDeviceView.scanButton addTarget:self action:@selector(didClickScanDeviceButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bindDeviceView;
}


#pragma mark --- 设置视图布局
- (void)masLayoutSubview
{
    __weak UIView *superView = self.view;
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(px1920Height(262));
        make.left.mas_equalTo(superView.mas_left).with.offset(px1080Width(40));
        make.right.mas_equalTo(superView.mas_right).with.offset(-px1080Width(40));
        make.bottom.mas_equalTo(superView.mas_bottom);
    }];
    
    [self.bindDeviceView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.left.right.bottom.mas_equalTo(superView);
    }];
    
}

- (void)setNavigationStyle
{
    [self setLeftButtonImage:nil];
    [self setNavigationBarTitle:@"聊天"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
